package com.adun.springsecurityoauth2demo.config;

import com.adun.springsecurityoauth2demo.service.ClientDetailServiceImpl;
import com.adun.springsecurityoauth2demo.service.UserDetailServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.security.oauth2.provider.token.TokenEnhancerChain;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Zhu Dunfeng
 * @date 2021/7/12 22:52
 *
 * 授权服务器配置
 */
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private UserDetailServiceImpl userDetailServiceImpl;

//    @Autowired
//    @Qualifier("redisTokenStore")
//    private TokenStore tokenStore;

    @Autowired
    @Qualifier("jwtTokenStore")
    private TokenStore tokenStore;

    @Autowired
    private JwtAccessTokenConverter jwtAccessTokenConverter;

    /**
     * 注入jwt扩展配置
     */
    @Autowired
    private JwtTokenEnhancer jwtTokenEnhancer;

    @Autowired
    private ClientDetailServiceImpl clientDetailServiceImpl;

    /**
     * 密码模式
     * @param endpoints
     * @throws Exception
     */
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        //设置JWT增强内容
        TokenEnhancerChain chain = new TokenEnhancerChain();
        List<TokenEnhancer> delegates = new ArrayList<>();
        delegates.add(jwtTokenEnhancer);
        delegates.add(jwtAccessTokenConverter);
        chain.setTokenEnhancers(delegates);

        endpoints
                .authenticationManager(authenticationManager)
                //自定义的用户登录信息
                .userDetailsService(userDetailServiceImpl)
                //redis保存token值
//                .tokenStore(tokenStore);

                //使用OAuth2的jwt
                //accessToken转成JWTtoken
                .tokenStore(tokenStore)
                .accessTokenConverter(jwtAccessTokenConverter)

                //jwt扩展字段
                .tokenEnhancer(chain);
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
                //可结合数据库进行client认证
                // .clients(clientDetailServiceImpl)
                //客户端id
                .withClient("client")
                //密钥
                .secret(passwordEncoder.encode("112233"))
                //重定向地址
//                .redirectUris("http://www.baidu.com")
                .redirectUris("http://www.baidu.com","http://localhost:8081/login")
                //授权范围
                .scopes("all")
                //accessToken失效时间
                .accessTokenValiditySeconds(60)
                //refreshToken失效时间
                .refreshTokenValiditySeconds(60*5)
                //自动授权,(不写需要手动点击授权)
                .autoApprove(true)
                /**
                 * 授权类型
                 * authorization_code:授权码模式
                 *
                 * 授权码模式: authorization_code
                 * 授权码简化模式: implicit
                 * 密码模式: password
                 * 客户端模式: client_credentials
                 *
                 * refresh_token:刷新令牌
                 */
                .authorizedGrantTypes("authorization_code","password","client_credentials","implicit","refresh_token");
    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        //必须压迫身份认证，单点登录必须配置
        security.tokenKeyAccess("isAuthenticated()");
    }
}
